package com.controller;

import com.pojo.Bill;
import com.pojo.Provider;
import com.service.BillService;
import com.service.ProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class BillController {

    @Autowired
    private BillService billService;

    @Autowired
    private ProviderService providerService;


    @RequestMapping("/billList.do")
    public String billList(HttpSession session){
        List<Bill> list = billService.findAll();
        List<Provider> proList = providerService.findAll();
        session.setAttribute("proList",proList);
        session.setAttribute("billList",list);
        return "billList";
    }

    @RequestMapping("/billAddView.do")
    public String billAddView(HttpSession session){
        List<Provider> proList = providerService.findAll();
        session.setAttribute("proList",proList);
        return "billAdd";
    }

    @RequestMapping("/billAdd.do")
    public String billAdd(Bill bill){
        Boolean isok = billService.doAddBillService(bill);
        if (isok){
            return "redirect:billList.do";
        }
        return "error";
    }

    @RequestMapping("/billView.do")
    public String billView(Long id,HttpSession session){
        Bill bill = billService.findBillByid(id.intValue());
        session.setAttribute("billView",bill);
        return "billView";
    }

    @RequestMapping("/billUpdateView.do")
    public String billUpdateView(Long id,HttpSession session){
        Bill bill = billService.findBillByid(id.intValue());
        List<Provider> proList = providerService.findAll();
        session.setAttribute("proList",proList);
        session.setAttribute("billView",bill);
        return "billUpdate";
    }

    @RequestMapping("/billUpdate.do")
    public String billUpdate(Bill bill){
        Boolean isok = billService.doUpdateBillService(bill);
        if (isok){
            return "forward:billView.do";
        }
        return null;
    }

    @ResponseBody
    @RequestMapping("/billDelete.do")
    public String billDelete(String id){
        Boolean isok = billService.doDeleteBillService(Integer.valueOf(id));
        if (isok){
            return "true";
        }
        return "false";
    }

    @RequestMapping("/billSearch.do")
    public String billSearch(Bill bill,HttpSession session){
        System.out.println(bill);
        if (bill.getIsPayment()==null && bill.getProviderId().getId()==null && bill.getProductName()==""){
            return "redirect:billList.do";
        }
        List<Bill> list = billService.findSearchBill(bill);
        session.setAttribute("billList",list);
        return "billList";
    }
}
